﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class P2_BAKController : MonoBehaviour {

	//animate config
	private float duration = 0.2f;	//动画时长
	private int maxPokerNums = 13;	//牌数

	//room info
	public UILabel roomType;
	public UILabel roomRound;
	public UILabel roomNumber;

	 //mine
	public GameObject minePanel;
	public GameObject mineAvatar;
	public GameObject mineMaster;
	public UISprite mineStatus;
	public UILabel mineName;
	public UILabel mineScore;

	public UISprite minePokerPanel;
	private List<UISprite> minePokers = new List<UISprite>(); 	//我的牌
	private List<UISprite> pickPokers = new List<UISprite> ();	//选中的牌
	private List<UISprite> hasPick = new List<UISprite> ();			//提交的牌

	//other
	public GameObject otherPanel;
	public GameObject otherAvatar;
	public GameObject otherMaster;
	public UISprite otherStatus;
	public UILabel otherName;
	public UILabel otherScore;
	public UISprite otherPokerPanel;
	private List<UISprite> otherPokers = new List<UISprite>();

	public UIAtlas atlas;
	public UISprite readyButton;
	private bool isReady = false;

	private User mine;
	private User other;

	//牌型
	public UIPanel paixingPanel;
	private List<UISprite> paixingList = new List<UISprite> ();
	private Dictionary<string,List<string[]>> paixingCombo = new Dictionary<string, List<string[]>> ();
	public List<UISprite> pickPokerList = new List<UISprite> ();
	public UISprite duiziSprite;
	public UISprite liangduiSprite;
	public UISprite santiaoSprite;
	public UISprite shunziSprite;
	public UISprite huluSprite;
	public UISprite tonghuaSprite;
	public UISprite tonghuashunSprite;
	public UISprite zhadanSprite;

	//选牌
	public GameObject pickPanel;
	public GameObject sureButton;
	public GameObject cancelButton;

	//结果
	public GameObject mineResultPanel;
	public GameObject otherReultPanel;

	//重开
	public GameObject restartPanel;
	public GameObject mineResultInfoPanel;
	public GameObject otherResultInfoPanel;
	public UIButton leaveButton;
	public UIButton shareButton;
	public UIButton restartButton;

	// Use this for initialization
	void Start () {
//		ReadyClick();

		//初始化对手信息未空

		ReadyStatus();


		paixingList.Add(duiziSprite);
		paixingList.Add(liangduiSprite);
		paixingList.Add(santiaoSprite);
		paixingList.Add(shunziSprite);
		paixingList.Add(huluSprite);
		paixingList.Add(tonghuaSprite);
		paixingList.Add(zhadanSprite);
		paixingList.Add(tonghuashunSprite);

		foreach (var sprite in paixingList) {
			BoxCollider boxcollider = sprite.gameObject.AddComponent<BoxCollider> ();
			boxcollider.center = new Vector3 (400, -200);
			boxcollider.size = new Vector3 (800, 400);
			UIEventListener.Get (sprite.gameObject).onClick += AutoPrompt;	
		}

		setDefaultStatus ();

		//在接收者中注册事件及其回调方法
//		NotificationCenter.Get().AddEventListener(API.ROOM_ACTION, HandlerRoomFrame);
//		NotificationCenter.Get().AddEventListener(API.USER_ACTION, HandlerRoomExit);
//
//		HandlerRoomFrame (null);
//
//	}
//
//	void OnDestroy(){
//		Debug.Log ("移除监听");
//		NotificationCenter.Get ().RemoveEventListener (API.ROOM_ACTION, HandlerRoomFrame);
//		NotificationCenter.Get ().RemoveEventListener (API.USER_ACTION,HandlerRoomExit);
	}


	// Update is called once per frame
	void Update () {
		
	}

	//设置默认布局
	private void setDefaultStatus(){

		minePokers.Clear ();
		hasPick.Clear ();
		pickPokers.Clear ();
		foreach (var p in pickPokerList) {
			p.spriteName = "null";
		}
		//清除敌方牌面
		foreach (var p in otherPokers) {
			Destroy (p);
		}
		otherPokers.Clear ();
		
		IsShowPaixing (false);

		//初始化牌型
		ClearPickerPanel (0);
		pickPanel.SetActive(false);
		sureButton.SetActive (false);
		cancelButton.SetActive (false);

		//初始化结果界面
		restartPanel.SetActive (false);
		minePokerPanel.gameObject.SetActive (false);

		restartPanel.SetActive(false);
	}

	public void ReadyClick(){
		isReady = !isReady;
		Debug.Log ("ReadyStatus:" + isReady.ToString ());

		if (isReady) {
			readyButton.spriteName = "Cancel";
			mineStatus.gameObject.SetActive (true);
			mineStatus.spriteName = "Icon Ready";
		}else{
			readyButton.spriteName = "Ready";
			mineStatus.gameObject.SetActive (false);
		}

		API.ChangeRoomStatus (isReady);
	}

	public void HandlerRoomFrame(object obj){
		
		//检测用户和状态
//		ReadyStatus ();
//		//检测房间状态并摆牌
//		RoomStatus();

		//刷新房间信息
//		roomType.text = Main.room.payMethod + "/"+Main.room.playerNum.ToString()+"人";
//		roomRound.text = "第" + Main.room.curRound.ToString() + "/" +Main.room.maxRound.ToString() + "局";
//		roomNumber.text = "房间号："+Main.room.id;

	}

	public void HandlerRoomExit(object obj){
		Debug.Log ("退出房间通知");
	}

	public void RoomStatus(){

		if (Main.user.status == USER_STATUS.FREE.GetHashCode ()) {
			SceneManager.LoadScene ("Home");
		}
		
		if (mine.status < USER_STATUS.CAN_ACTION.GetHashCode()) {
			readyButton.gameObject.SetActive (true);
			IsShowPaixing (false);
			mineResultPanel.SetActive (false);
			otherReultPanel.SetActive (false);
			return;
		} else {
			readyButton.gameObject.SetActive (false);
		}

		//摆牌状态
		if (other != null && mine.status == USER_STATUS.BEFORE_SUBMIT.GetHashCode () && !minePokerPanel.gameObject.activeInHierarchy) {
			//显示我方牌
			setDefaultStatus ();
			ShowMinePoker ();
		}

		//显示摆完牌等待界面
		if (other != null && Main.user.status == USER_STATUS.AFTER_SUBMIT.GetHashCode ()) {
			MineAfterSubmit ();
		}

		//敌方摆牌状态
		if (other != null && other.status == USER_STATUS.BEFORE_SUBMIT.GetHashCode ()) {
			//显示敌方牌
			ShowOtherPoker ();
		}

		//敌方提交完成后状态
		if (other != null && other.status == USER_STATUS.AFTER_SUBMIT.GetHashCode ()) {
			OtherAfterSubmit ();
		}

		//在比牌状态
		if(other != null && Main.room.status == ROOM_STATUS.SHOW_SCORES.GetHashCode() && !restartPanel.activeInHierarchy){
			ShowResult ();
		}

	}

	//我方提交后显示
	public void MineAfterSubmit(){
		//己方
		pickPanel.SetActive (false);
		sureButton.SetActive (false);
		cancelButton.SetActive (false);
		mineResultPanel.SetActive (true);
		readyButton.gameObject.SetActive (false);
		paixingPanel.gameObject.SetActive (false);
		for (int i = 0; i < 13; i++) {
			UISprite sprite = mineResultPanel.transform.GetChild (i).gameObject.GetComponent<UISprite>();	
			UISprite sprite2 = otherReultPanel.transform.GetChild (i).gameObject.GetComponent<UISprite>();	
			sprite.spriteName = "Card";
			sprite2.spriteName = "Card";
		}
		for (int i = 13; i < 19; i++) {
			mineResultPanel.transform.GetChild (i).gameObject.SetActive (false);	
		}
	}
	public void OtherAfterSubmit(){
		//清除其他牌面
		foreach (var p in otherPokers) {
			Destroy (p);
		}
		otherPokers.Clear ();

		otherReultPanel.SetActive (true);
		for (int i = 13; i < 19; i++) {
			otherReultPanel.transform.GetChild (i).gameObject.SetActive (false);	
		}
	}

	//摆我方牌
	public void ShowMinePoker(){
		mineResultPanel.gameObject.SetActive (false);
		minePokers.Clear ();

		minePokerPanel.gameObject.SetActive (true);
		Bounds bounds = minePokerPanel.CalculateBounds ();
		float x = (bounds.max.x   - bounds.min.x) / maxPokerNums;//得到相应素材图片的高度

		for (int i = 0; i < maxPokerNums; i++) {

			//Utils.getLocalPorker (mine.cardList [i])
			//放置位置，并隐藏
			UISprite sprite = NGUITools.AddSprite(minePokerPanel.gameObject,atlas,"Card");
			minePokers.Add (sprite);

			//己方位置
			float positionX = x * minePokers.IndexOf (sprite);
//			Debug.Log ("设置位置：" + positionX);
			sprite.alpha = 0;
			sprite.transform.localScale = new Vector3(5,6,1);
			float cardWidth = (sprite.CalculateBounds ().max.x - sprite.CalculateBounds ().min.x);
			sprite.transform.localPosition = new Vector3( positionX - ((bounds.max.x   - bounds.min.x) /2) +cardWidth,0,-10);
			sprite.transform.localRotation = new Quaternion (0, 90, 0, 1);

			//延时动画
			StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
				{
					TweenAlpha.Begin(sprite.gameObject,0.1f,1);
					TweenRotation.Begin(sprite.gameObject,0.1f,new Quaternion (0, 0, 0, 1));
				}, (0.1f * i)));
//				}, (duration * i)));

			//发牌音效
			EffectUtil.FaPai();

			//翻牌
			if (i == 12) {
				StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
					{
						CheckPaixing();
						OpenCards();
						IsShowPaixing (true);
					}, duration * maxPokerNums));
			}
		}

	}

	//摆敌方牌
	public void ShowOtherPoker(){
		otherPokerPanel.gameObject.SetActive (true);
		otherReultPanel.gameObject.SetActive (false);

		if (otherPokers.Count > 0) {
			return;
		}

		Bounds otherBounds = otherPokerPanel.CalculateBounds ();
		float x2 = (otherBounds.max.x   - otherBounds.min.x) / maxPokerNums;//得到相应素材图片的高度
		for (int i = 0; i < maxPokerNums; i++) {
			UISprite otherSprite = NGUITools.AddSprite(otherPokerPanel.gameObject,atlas,"Card");

			otherPokers.Add (otherSprite);

			//敌方位置
			float positionX2 = x2 * otherPokers.IndexOf (otherSprite);
			otherSprite.alpha = 0;
			otherSprite.transform.localScale = new Vector3(3,4,1);
			float cardWidth2 = (otherSprite.CalculateBounds ().max.x - otherSprite.CalculateBounds ().min.x);
			otherSprite.transform.localPosition = new Vector3(positionX2 - ((otherBounds.max.x - otherBounds.min.x) /2) +cardWidth2,0,-10);
			otherSprite.transform.localRotation = new Quaternion (0, 90, 0, 1);

			//延时动画
			StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
				{
					TweenAlpha.Begin(otherSprite.gameObject,0.1f,1);
					TweenRotation.Begin(otherSprite.gameObject,0.1f,new Quaternion (0, 0, 0, 1));
				}, (0.1f * i)));
		}
	}

	//显示结果
	public void ShowResult(){

		EffectUtil.KaishiBiPai (Main.user.sex);

		//清除其他牌面
		foreach (var p in otherPokers) {
			Destroy (p);
		}
		otherPokers.Clear ();

		JSONObject mineResult = null;
		JSONObject otherResult = null;
		if (Main.room.data ["results_list"] [0] ["player_id"].ToString () == Main.user.id) {
			mineResult = Main.room.data ["results_list"] [0];
			otherResult = Main.room.data ["results_list"] [1];
		} else {
			mineResult = Main.room.data ["results_list"] [1];
			otherResult = Main.room.data ["results_list"] [0];
		}
		//我的结果
		ShowResultDetail(mineResult,mineResultPanel,mine.sex);
		//对方的结果，延时执行
		StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				ShowResultDetail(otherResult,otherReultPanel,other.sex);
			}, 1f));

		StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				ShowRestartPanel();
			}, 10f));

		if (int.Parse (mineResult ["multiple"].ToString ()) > 1) {
			Debug.Log ("打枪");
			StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
				{
					EffectUtil.DaQiang(Main.user.sex);
				}, 8f));
		}

		if (int.Parse (otherResult ["multiple"].ToString ()) > 1) {
			Debug.Log ("打枪");
			StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
				{
					EffectUtil.DaQiang(other.sex);
				}, 8f));
		}

	}

	//显示结果详情,并检测是否可以继续游戏
	private void ShowResultDetail(JSONObject result,GameObject panel,int sex){
		

		float dur1 = 2f;
		float dur2 = 4f;
		float dur3 = 6f;
		//显示牌型
		for(int i = 0;i<13;i++){
			float dur = 0;
			UISprite sprite = panel.transform.GetChild (i).gameObject.GetComponent<UISprite>();	
			if (i < 3) {
				sprite.spriteName = Utils.getLocalPorker (result ["submit_res_cards"] ["top"].list [i].str);		
				dur = dur1;
			} else if (i < 8) {
				sprite.spriteName = Utils.getLocalPorker (result ["submit_res_cards"] ["mid"].list [i - 3].str);
				dur = dur2;
			}else {
				sprite.spriteName = Utils.getLocalPorker (result ["submit_res_cards"] ["btm"].list [i - 8].str);		
				dur = dur3;
			}
			sprite.alpha = 0;
			sprite.transform.localRotation = new Quaternion (0, 90, 0, 1);

			StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
				{
					TweenAlpha.Begin(sprite.gameObject,duration,1);
					TweenRotation.Begin(sprite.gameObject,duration,new Quaternion (0, 0, 0, 1));
				}, (dur)));
		}

		//显示分数 16,17,18
		UILabel topLabel = panel.transform.GetChild (16).gameObject.GetComponent<UILabel>();	
		topLabel.text = result ["one_vs_one_list"] [0] ["top"].ToString();
		topLabel.gameObject.SetActive (true);
		topLabel.alpha = 0;
		UILabel midLabel = panel.transform.GetChild (17).gameObject.GetComponent<UILabel>();	
		midLabel.text = result ["one_vs_one_list"] [0] ["mid"].ToString();
		midLabel.gameObject.SetActive (true);
		midLabel.alpha = 0;
		UILabel btmLabel = panel.transform.GetChild (18).gameObject.GetComponent<UILabel>();
		btmLabel.text = result ["one_vs_one_list"] [0] ["btm"].ToString();
		btmLabel.gameObject.SetActive (true);
		btmLabel.alpha = 0;


		StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				TweenAlpha.Begin(topLabel.gameObject,duration,1);
				TweenAlpha.Begin(midLabel.gameObject,duration,1);
				TweenAlpha.Begin(btmLabel.gameObject,duration,1);
			}, (8f)));
		
		//显示是否什么牌型
		UISprite line1 = Utils.ShowResultPaixing(result["submit_res_scores"]["top"]["handle_weight"].ToString(),
			panel.transform.GetChild (13).gameObject.GetComponent<UISprite>());
		UISprite line2 = Utils.ShowResultPaixing(result["submit_res_scores"]["mid"]["handle_weight"].ToString(),
			panel.transform.GetChild (14).gameObject.GetComponent<UISprite>());
		UISprite line3 = Utils.ShowResultPaixing(result["submit_res_scores"]["btm"]["handle_weight"].ToString(),
			panel.transform.GetChild (15).gameObject.GetComponent<UISprite>());


		StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				TweenAlpha.Begin(line1.gameObject,duration,1);
//				EffectUtil.PlayWithPaixing(result["submit_res_scores"]["top"]["handle_weight"].ToString(),sex);
			}, (dur1)));
		StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				TweenAlpha.Begin(line2.gameObject,duration,1);
//				EffectUtil.PlayWithPaixing(result["submit_res_scores"]["mid"]["handle_weight"].ToString(),sex);
			}, (dur2)));
		StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				TweenAlpha.Begin(line3.gameObject,duration,1);
//				EffectUtil.PlayWithPaixing(result["submit_res_scores"]["btm"]["handle_weight"].ToString(),sex);
			}, (dur3)));
	}


	//翻牌
	public void OpenCards(){
		foreach (var s in minePokers) {
			s.spriteName = Utils.getLocalPorker(mine.cardList [minePokers.IndexOf(s)]);	
		}

		StartCoroutine(DelayToInvoke.DelayToInvokeDo(() =>
			{
				//整体位置下移
				Debug.Log("位置移动到:"+minePanel.transform.position.y.ToString());
				TweenPosition.Begin(minePokerPanel.gameObject,1,
					new Vector3(0,-1000,-10));
			}, 0.5f));

		//动画完成后添加事件
		StartCoroutine (DelayToInvoke.DelayToInvokeDo (() => {
			foreach (var sprite in minePokers) {
				//己方牌添加事件
				BoxCollider boxcollider = sprite.gameObject.AddComponent<BoxCollider> ();
				boxcollider.size = new Vector3 (100, 100);
				UIEventListener.Get (sprite.gameObject).onClick += IsPokerShow;	
			}

			pickPanel.SetActive(true);
		}, 0.5f * maxPokerNums / 4));

		//延时音效
		StartCoroutine (DelayToInvoke.DelayToInvokeDo (() => {
			EffectUtil.QingChuPai();
		}, 2f));
			
		//牌型提示
		CheckPaixing();

		Debug.Log("屏幕宽度："+paixingPanel.width);

		float width = paixingPanel.width / (paixingList.Count);
		int i = 0;
		foreach(var px in paixingList){
			Vector3 curr = px.transform.position;
			px.width = (int)width;
			px.transform.position = new Vector3(( (float)(i * width * 0.99) - (paixingPanel.width / 2) ) / 360,curr.y,curr.z);
			Debug.Log(px.transform.position);
			i++;
		}

	}

	//检测用户和状态
	public void ReadyStatus(){
		foreach (var u in Main.room.players) {
			if (u.id != Main.user.id) {
				other = u;
			}
		}
		mine = Main.user;

		//对手信息
		if (other != null) {
			otherName.text = other.username;
			otherScore.text = other.points.ToString ();
			Utils.checkPlayerStatus (otherStatus, other);
		} else {
			otherName.text = "等待玩家加入...";
			otherStatus.spriteName = "null";
			otherScore.text = "0";
		}

		//我的信息
		mineName.text = mine.username;
		mineScore.text = mine.points.ToString();
		Utils.checkPlayerStatus (mineStatus, mine);

		//确定房主
		if (Main.room.owner.id == mine.id) {
			mineMaster.SetActive (true);
			otherMaster.SetActive (false);
		} else {
			mineMaster.SetActive (false);
			otherMaster.SetActive (true);
		}
	}

	//检测牌型
	private void CheckPaixing(){
		//清空牌型
		paixingCombo.Clear();

		var cl = new CardList();

		//去除已选的牌检测
		List<string> surplusCards =  new List<string>(Main.user.cardList);

		foreach (var i in hasPick) {
			string p = Utils.getServerPorker (i.spriteName);
			surplusCards.Remove (p);
		}

		paixingCombo = Utils.PaixingCombo (cl,surplusCards.ToArray());

		//检测哪些牌型亮起
		LightPaixing(duiziSprite,"duizi");
		LightPaixing(liangduiSprite,"liangdui");
		LightPaixing(santiaoSprite,"santiao");
		LightPaixing(shunziSprite,"shunzi");
		LightPaixing(huluSprite,"hulu");
		LightPaixing(tonghuaSprite,"tonghua");
		LightPaixing(zhadanSprite,"zhadan");
		LightPaixing(tonghuashunSprite,"tonghuashun");
	}
	//点亮牌型
	private void LightPaixing(UISprite sprite,string key){
		List<string[]> items = new List<string[]> ();
		if (paixingCombo.ContainsKey (key)) {
			paixingCombo.TryGetValue (key, out items);
		}
		sprite.spriteName = key + "_0" + (items.Count > 0 ? "1":"2");
	}

	//是否显示牌型提示
	private void IsShowPaixing(bool show){
		paixingPanel.gameObject.SetActive (show);
		foreach (var px in paixingList) {
			px.gameObject.SetActive (show);
		}
	}


	//牌型提示
	private void AutoPrompt(GameObject gameObject){
		UISprite sprite = gameObject.GetComponent<UISprite> ();
		string key = sprite.spriteName.Split ('_') [0];
		List<string[]> combos = new List<string[]> ();
		paixingCombo.TryGetValue (key,out combos);
		if (combos.Count == 0) {
			return;
		}

		//清空所有牌的选中状态
		foreach(var p in minePokers){
			Debug.Log ("自动隐藏:"+p.spriteName);
			if (pickPokers.Contains (p)) {
				IsPokerShow (p.gameObject);
			}
		}

		//添加选中状态

		string[] combo = combos[0];
		foreach (var c in combo) {
			foreach (var p in minePokers) {
				if (Utils.getServerPorker (p.spriteName).Equals (c)) {
					//如果匹配,选中状态
					IsPokerShow(p.gameObject);
					break;
				}
			}
		}
		combos.RemoveAt(0);
		combos.Add (combo);
	}

	//展示重开界面
	private void ShowRestartPanel(){

		//是否可以继续游戏
		if (Main.room.curRound > 0) {
			restartButton.GetComponent<UISprite> ().spriteName = "Icon Continue1";
			restartButton.isEnabled = true;
		} else {
			//我是房主
			if (Main.room.owner.id == mine.id) {
				restartButton.GetComponent<UISprite> ().spriteName = "Icon Recharge1";
			} else {
				restartButton.isEnabled = false;
			}
		}

		if (restartPanel.activeInHierarchy) {
			return;
		}
		//展示信息
		restartPanel.SetActive (true);
		SetRestartPanelInfo (mineResultInfoPanel, mine);
		SetRestartPanelInfo (otherResultInfoPanel, other);



	}

	private void SetRestartPanelInfo(GameObject panel,User info){
		//头像
		UITexture texture = panel.transform.GetChild (0).GetComponent<UITexture>();
		UILabel name = panel.transform.GetChild (1).GetComponent<UILabel>();
		UILabel id = panel.transform.GetChild (2).GetComponent<UILabel>();
		UILabel point = panel.transform.GetChild (3).GetComponent<UILabel>();

		name.text = info.username;
		id.text = "ID:" + info.id;
	}

	//点击继续游戏或续费
	public void RestartGameClick(){
		if (Main.room.curRound > 0) {
			//发送重新开始游戏事件
			API.RestartGame();
			//隐藏部分界面
			minePokerPanel.gameObject.SetActive (false);
			restartPanel.SetActive(false);
			mineResultPanel.SetActive (false);
			otherReultPanel.SetActive (false);

			for(int i = 13;i<19;i++){
				if (i < 16) {
					mineResultPanel.transform.GetChild (i).gameObject.GetComponent<UISprite> ().gameObject.SetActive (false);	
					otherReultPanel.transform.GetChild (i).gameObject.GetComponent<UISprite> ().gameObject.SetActive (false);
				} else {
					mineResultPanel.transform.GetChild (i).gameObject.GetComponent<UILabel> ().gameObject.SetActive (false);	
					otherReultPanel.transform.GetChild (i).gameObject.GetComponent<UILabel> ().gameObject.SetActive (false);
				}
			}

			ReadyClick();

			//清空敌方牌
			foreach (var p in otherPokers) {
				p.RemoveFromPanel ();
				Destroy (p);
			}
			//清空我方牌
			foreach(var p in minePokers){
				p.RemoveFromPanel ();
				Destroy (p);
			}
		}else{
			API.RechargeGame ();
		}
	}


	//离开房间
	public void LeaveRoomClick(){
		API.LeaveRoom ();
	}


	//是否选中待选牌
	private void IsPokerShow(GameObject gameObject){
		UISprite card = gameObject.GetComponent<UISprite>();
		float distance = 100;
		if (!pickPokers.Contains (card)) {
			pickPokers.Add (card);
		} else {
			distance = 0;
			pickPokers.Remove (card);
		} 
		TweenPosition.Begin (card.gameObject, 0.1f, 
			new Vector3 (card.transform.position.x * 360, (card.transform.position.y + distance), -10));

		Debug.Log ("点击："+card.spriteName);
	}

	public void PickUpLine1(){
		PickUpLine (1);
	}
	public void PickUpLine2(){
		PickUpLine (2);
	}
	public void PickUpLine3(){
		PickUpLine (3);
	}

	//点击放到三道里
	private void PickUpLine(int line){
		if ( (line == 1 && pickPokers.Count != 3)
			||(line == 2 && pickPokers.Count != 5)
			||(line == 3 && pickPokers.Count != 5)
		) {
			Debug.Log ("未满足条件");
			return;
		}
		//检测是否覆盖选择
		if ((line == 1 && pickPokerList [0].gameObject.activeInHierarchy) ||
		   (line == 2 && pickPokerList [3].gameObject.activeInHierarchy) ||
		   (line == 3 && pickPokerList [8].gameObject.activeInHierarchy)) {
			Debug.Log ("覆盖");
			return;
		}

		if (line == 0) {
			foreach (var p in pickPokerList) {
				if (!p.gameObject.activeInHierarchy) {
					p.spriteName = pickPokers [0].spriteName;
					pickPokers [0].gameObject.SetActive (false);
					hasPick.Add (pickPokers [0]);
					pickPokers.RemoveAt (0);
					p.gameObject.SetActive (true);
				}
			}
		} else {
			int start = line == 1 ? 0 : line == 2 ? 3 : line == 3 ? 8 : 0;
			for (int i = 0; i < pickPokers.Count; i++) {
				pickPokerList [i + start].gameObject.SetActive (true);
				pickPokerList [i+start].spriteName = pickPokers [i].spriteName;	
				pickPokers [i].gameObject.SetActive (false);
				hasPick.Add (pickPokers [i]);
			}	
		}
		pickPokers.Clear ();

		//检测是否剩余
		if(hasPick.Count == 8 || hasPick.Count == 10){
			foreach (var p in minePokers) {
				if (p.gameObject.activeInHierarchy) {
					pickPokers.Add (p);
				}
			}
			PickUpLine (0);
		}

		if (hasPick.Count == 13) {
			sureButton.SetActive (true);
			cancelButton.SetActive (true);
		} else {
			sureButton.SetActive (false);
			cancelButton.SetActive (false);
		}

		//重新检测牌型
		CheckPaixing ();
	}

	public void Submit(){
		List<string> pokers = new List<string> ();
		foreach (var p in pickPokerList) {
			pokers.Add (Utils.getServerPorker (p.spriteName));
		}
		API.Submit (pokers.GetRange (0, 3).ToArray (), pokers.GetRange (3, 5).ToArray (), pokers.GetRange (8, 5).ToArray ());
	}

	public void ClearPickerLineAll(){
		ClearPickerPanel (0);
	}
	public void ClearPickerLine1(){
		ClearPickerPanel (1);
	}
	public void ClearPickerLine2(){
		ClearPickerPanel (2);
	}
	public void ClearPickerLine3(){
		ClearPickerPanel (3);
	}

	private void ClearPickerPanel(int line){
		int start = (line == 0 || line == 1?0: line == 2? 3 : line == 3 ? 8:0);
		int end = (line == 0?13: line == 1 ? 3 : line == 2? 8 : line == 3 ? 13:13);
		for (int i = start; i < end; i++) {
			UISprite sprite = pickPokerList [i];
			//重新显示牌
			foreach(var p in minePokers){
				if (p.spriteName.Equals (sprite.spriteName)) {
					p.gameObject.SetActive (true);
					//从已选择中去除
					hasPick.Remove (p);
					TweenPosition.Begin (p.gameObject, 0.1f, 
						new Vector3 (p.transform.position.x * 360, p.transform.position.y, -10));
				}
			}

			//设置面板
			pickPokerList[i].gameObject.SetActive(false);
			pickPokerList[i].spriteName = "null";
		}
		if (hasPick.Count == 13) {
			sureButton.SetActive (true);
			cancelButton.SetActive (true);
		} else {
			sureButton.SetActive (false);
			cancelButton.SetActive (false);
		}

		//重新检测牌型
		CheckPaixing ();
	}

}
